import json
import random
import time

import redis
import requests

from flask import make_response , redirect
from flask_restful import reqparse , Resource
from application.tools.myjwt import myjwt
from application.tools.captcha import captcha
from application.tools.comm import send_message
from application.tools.myredis import r
from application.models.users.user import SfLogin
from application.models.users.user import *
from db import db
from flask_restful import Resource , Api
from application.models.users.user import User
from flask import Blueprint , request , jsonify

good_blue = Blueprint ( "goodblue" , __name__ )

api =Api(good_blue)

# 获取训练营里面得所有数据

@good_blue.route ( '/getxly' )
def getxly() :
    sql = 'select * from tcourse'
    res = db.find_all ( sql )
    return jsonify ( { 'code' : 200 , 'msg' : 'ok' , 'data' : res } )


# 加入购物车
@good_blue.route ( '/addgood' , methods=["POST"] )
def addshop() :
    req = reqparse.RequestParser ()
    req.add_argument ( 'userid' )
    req.add_argument ( 'id' )
    args = req.parse_args ()
    if not all ( { args['userid'] , args['id'] } ) :
        return jsonify ( { 'code' : 400 , 'msg' : '数据不存在' } )

    cart = Cart.query.filter ( Cart.cid == args['id'] ).first ()
    print ( cart )
    if cart :
        sql = "update Cart set count=count+1 where cart.cid=%d" % int ( args['id'] )
        db.add ( sql )
        db.commit ()
        return jsonify ( { 'code' : 200 , 'msg' : 'ok' } )
    else :
        count = 1
        sql = "insert into cart(userid,cid,count) values('%d','%d','%d')" % (
        int ( args['userid'] ) , int ( args['id'] ) , int ( count ))
        db.add ( sql )
        db.commit ()
        return jsonify ( { 'code' : 200 , 'msg' : '加入购物车成功' } )


# 展示购物车数据
@good_blue.route ( '/getcourse' , )
def gettcourse() :
    uid = request.args.get ( 'userid' )
    list = []
    sql = "select * from cart where cart.userid=%d" % int ( uid )
    res = db.find_all ( sql )
    for i in res :
        sql1 = "select * from tcourse where tcourse.id=%d" % int ( i['cid'] )
        res1 = db.find_all ( sql1 )
        for j in res1 :
            list.append ( {
                'id' : j['id'] ,
                'title' : j['title'] ,
                'price' : j['price'] ,
                'count' : i['count'] ,
                'url' : j['url'] ,
                'amount' : (j['price'] * i['count'])
            } )
    return jsonify ( { 'code' : 200 , 'msg' : 'ok' , 'data' : list } )


# 购物车数量加
@good_blue.route ( '/addcount' , methods=["POST"] )
def Add_count() :
    req = reqparse.RequestParser ()
    req.add_argument ( 'userid' )
    req.add_argument ( 'id' )
    args = req.parse_args ()

    if not all ( { args['id'] , args['userid'] } ) :
        return jsonify ( { 'code' : 400 , 'msg' : '数据不存在' } )

    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int ( args['userid'] ) , int ( args['id'] ))
    res = db.find_all ( sql )
    for i in res :
        sql1 = "update Cart set count=count+1 where cart.userid=%d and cart.cid=%d" % (
            int ( i['userid'] ) , int ( args['id'] ))
        db.add ( sql1 )
        db.commit ()
    return jsonify ( { 'code' : 200 , 'msg' : 'ok' } )


# 购物车数量减
@good_blue.route ( '/mincount' , methods=["POST"] )
def Min_count() :
    req = reqparse.RequestParser ()
    req.add_argument ( 'userid' )
    req.add_argument ( 'id' )
    args = req.parse_args ()
    if not all ( { args['id'] , args['userid'] } ) :
        return jsonify ( { 'code' : 400 , 'msg' : '数据不存在' } )

    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int ( args['userid'] ) , int ( args['id'] ))
    res = db.find_all ( sql )
    for i in res :
        sql1 = "update Cart set count=count-1 where cart.userid=%d and cart.cid=%d" % (
        int ( i['userid'] ) , int ( args['id'] ))
        db.add ( sql1 )
        db.commit ()
    return jsonify ( { 'code' : 200 , 'msg' : 'ok' } )


# 删除购物车数据
@good_blue.route ( '/delcount' , methods=["POST"] )
def Del_count() :
    req = reqparse.RequestParser ()
    req.add_argument ( 'userid' )
    req.add_argument ( 'id' )
    args = req.parse_args ()

    if not all ( { args['id'] , args['userid'] } ) :
        return jsonify ( { 'code' : 400 , 'msg' : '数据不存在' } )

    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int ( args['userid'] ) , int ( args['id'] ))
    res = db.find_all ( sql )
    for i in res :
        sql1 = "delete from cart where cart.userid=%d and cart.cid=%d" % (int ( i['userid'] ) , int ( args['id'] ))
        db.add ( sql1 )
        db.commit ()
    return jsonify ( { 'code' : 200 , 'msg' : 'ok' } )


from db import db

from application.tools.comm import get_ali_object


@good_blue.route ( '/settlement' , methods=["POST"] )
def settlement() :
    data = json.loads ( request.data )
    userid = int ( data["userid"] )
    tmoney = int ( data["tmoney"] )
    cid = int ( data["cid"] )
    # 幂等性token
    key = "mdtoken" + str ( userid )
    sum = 0
    sql = "select * from cart where userid=%d" % userid
    res = db.session.execute ( sql )
    if not res :
        return jsonify ( { "code" : 500 , "msg" : "没有该商品" } )
    sum += float ( tmoney )
    print ( sum )
    # 订单号
    number = int ( str ( userid ) + str ( random.randint ( 1000 , 9999 ) ) )
    create_time = datetime.datetime.strftime ( datetime.datetime.now () , "%Y-%m-%d %H:%M:%S" )
    update_time = datetime.datetime.strftime ( datetime.datetime.now () , "%Y-%m-%d %H:%M:%S" )
    status = 2
    # usql = Vipuser_course(courseid=cid,userid=userid)
    # db.session.add(usql)
    # print(usql,'////////////////////////////')
    isql = Orders ( create_time=create_time , update_time=update_time , userid=userid , courseid=cid , number=number ,
                    tmoney=sum , status=status , price=sum )
    db.session.add ( isql )
    db.session.commit ()
    print ( isql , '111111111111111111111111' )
    sqlcart = Cart.query.filter ( Cart.userid == userid ).first ()
    db.session.delete ( sqlcart )
    print ( sqlcart , '22222222222222222222222' )
    db.session.commit ()
    # 删除幂等性token
    r.del_key ( key )
    # 支付
    oreder_no = str ( number ) + "," + str ( 2 )
    alipay = get_ali_object ()
    query_params = alipay.direct_pay (
        subject=str ( userid ) + "购买课程" ,  # 商品简单描述
        out_trade_no=oreder_no ,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=sum ,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format ( query_params )  # 支付宝网关地址（沙箱应用）
    return jsonify ( {
        'code' : 200 ,
        'url' : pay_url
    } )


# 评论
@good_blue.route ( "/crecom" , methods=['POST'] )
def createes() :
    data = json.loads ( request.data )
    title = data['title']
    userid = int ( data['userid'] )
    pid = int ( data['pid'] )
    # userid = int(userid)
    # pid = int(pid)
    print ( userid , pid , title )
    if not pid :
        # 首个评论
        comm = Comment(title=title , userid=userid  , pid=pid )
        db.session.add ( comm )
        print ( ">>>>...." )
        db.session.commit ()
    else :
        com = Comment.query.filter ( Comment.id == pid ).first ()
        print ( "com" , com.id )
        if com :
            coms = Comment ( title=title , userid=userid , typepid=2 , pid=com.id )
            db.session.add ( coms )
            print ( coms , ">?" )
            coms_info = Comment.query.filter ( Comment.pid == pid ).first ()
            print ( coms_info , "///" )
            if not coms_info :
                coms.is_last = 1
                print ( "11" )
            else :
                coms.is_last = 0
                print ( "00" )
            db.session.commit ()
        else :
            return jsonify ( { "code" : 404 , "msg" : "评论已删除" } )
    return jsonify ( { "code" : 200 , "msg" : "ok" } )


# 获取评论
def showuser(data) :  # 封装方法 也可以写进类视图中
    list2 = []
    dict2 = { }
    for i in data :
        k = i['id']
        dict2[k] = i

    for j in data :
        pid = j['pid']
        if pid == 0 :  # 如果为空说明是第一级
            list2.append ( j )
        else :
            if 'son' not in dict2[pid] :  # 判断是否有下级分类
                dict2[pid]['son'] = []
            dict2[pid]['son'].append ( j )  # 添加进去
    return list2


class Comment(Resource):
    def get(self):
        user_list = Comment.query.all()
        user_all = []
        for i in user_list :
            a = {
                'id' : i.id ,
                'title' : i.title ,
                'tcount' : i.tcount ,
                'tviews' : i.tviews ,
                'is_last' : i.is_last ,
                'is_top' : i.is_top ,
                'userid' : i.userid ,
                'typepid' : i.typepid ,
                'pid' : i.pid ,
            }
            user_all.append ( a )
            db.session.commit()
        ss = showuser ( user_all )  # 调用方法 并传参
        return jsonify ( { 'code' : 200 , 'data' : ss } )

api.add_resource(Comment,"/comment")